import { View, Text, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Card, 
  Avatar,
  Cell,
  CellGroup
} from '@nutui/nutui-react-taro'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import './index.less'

export default function Profile() {
  const [userInfo, setUserInfo] = useState(null)
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    checkLogin()
  })

  useDidShow(() => {
    checkLogin()
  })

  const checkLogin = async () => {
    try {
      // 尝试多个可能的存储 key
      let user = Taro.getStorageSync('userInfo') || 
                 Taro.getStorageSync('user') || 
                 Taro.getStorageSync('loginUser')
      
      // 如果没有用户信息，创建一个模拟用户（开发阶段）
      if (!user) {
        user = {
          id: 1,
          phone: '138****8888',
          name: '优洁用户',
          avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
          memberLevel: '黄金会员',
          memberExpiry: '2025-06-30'
        }
        // 存储用户信息
        Taro.setStorageSync('userInfo', user)
        console.log('创建模拟用户信息')
      }
      
      setUserInfo(user)
    } catch (error) {
      console.log('获取用户信息失败:', error)
      // 开发阶段不跳转登录页，直接创建模拟用户
      const mockUser = {
        id: 1,
        phone: '138****8888',
        name: '优洁用户',
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
        memberLevel: '黄金会员',
        memberExpiry: '2025-06-30'
      }
      setUserInfo(mockUser)
      Taro.setStorageSync('userInfo', mockUser)
    } finally {
      setLoading(false)
    }
  }

  const handleMenuClick = (type) => {
    switch (type) {
      case 'orders':
        Taro.switchTab({
          url: '/pages/orders/index'
        })
        break
      case 'coupons':
        Taro.navigateTo({
          url: '/pages/coupons/index'
        })
        break
      case 'contact':
        Taro.showModal({
          title: '联系客服',
          content: '客服电话：400-888-8888\n工作时间：7×24小时',
          showCancel: false,
          confirmText: '知道了'
        })
        break
      case 'settings':
        Taro.navigateTo({
          url: '/pages/settings/index'
        })
        break
      default:
        Taro.showToast({
          title: '功能开发中',
          icon: 'none'
        })
        break
    }
  }

  if (loading) {
    return (
      <View className='profile-page'>
        <View className='loading-container'>
          <Text>加载中...</Text>
        </View>
      </View>
    )
  }

  if (!userInfo) {
    return (
      <View className='profile-page'>
        <View className='login-prompt'>
          <Text>请先登录</Text>
        </View>
      </View>
    )
  }

  return (
    <View className='profile-page'>
      {/* 用户信息区域 */}
      <View className='user-section'>
        <View className='user-info'>
          <Avatar 
            size='large'
            src={userInfo.avatar}
            className='user-avatar'
          />
          <View className='user-details'>
            <Text className='user-name'>{userInfo.name}</Text>
            <Text className='user-level'>{userInfo.memberLevel}</Text>
          </View>
        </View>
      </View>

      {/* 会员信息 */}
      <View className='member-section'>
        <Text className='section-title'>会员信息</Text>
        <View className='member-info'>
          <View className='member-item'>
            <Text className='member-label'>会员等级：</Text>
            <Text className='member-value'>{userInfo.memberLevel}</Text>
          </View>
          <View className='member-item'>
            <Text className='member-label'>到期时间：</Text>
            <Text className='member-value'>{userInfo.memberExpiry}</Text>
          </View>
        </View>
      </View>

      {/* 我的服务 */}
      <View className='services-section'>
        <Text className='section-title'>我的服务</Text>
        <CellGroup className='services-group'>
          <Cell
            title='我的订单'
            icon={<View className='menu-icon orders-icon'>📋</View>}
            isLink
            onClick={() => handleMenuClick('orders')}
            className='service-item'
          />
          <Cell
            title='我的优惠券'
            icon={<View className='menu-icon coupons-icon'>🎫</View>}
            isLink
            onClick={() => handleMenuClick('coupons')}
            className='service-item'
          />
          <Cell
            title='联系客服'
            icon={<View className='menu-icon contact-icon'>😊</View>}
            isLink
            onClick={() => handleMenuClick('contact')}
            className='service-item'
          />
          <Cell
            title='设置'
            icon={<View className='menu-icon settings-icon'>⚙️</View>}
            isLink
            onClick={() => handleMenuClick('settings')}
            className='service-item'
          />
        </CellGroup>
      </View>

      {/* 关于 */}
      <View className='about-section'>
        <Text className='section-title'>关于</Text>
        <View className='about-info'>
          <Text className='app-version'>App版本：1.0.0</Text>
        </View>
      </View>
    </View>
  )
}